#include "MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // Create UI
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    QVBoxLayout *layout = new QVBoxLayout(centralWidget);

    m_inputA = new QLineEdit(this);
    m_inputB = new QLineEdit(this);
    m_calculateButton = new QPushButton("Calculate A ÷ B", this);
    m_resultLabel = new QLabel("Result will appear here", this);

    layout->addWidget(new QLabel("Enter A:"));
    layout->addWidget(m_inputA);
    layout->addWidget(new QLabel("Enter B:"));
    layout->addWidget(m_inputB);
    layout->addWidget(m_calculateButton);
    layout->addWidget(m_resultLabel);

    // Create instance of DLL class
    m_calculator = new Calculator(this);

    // Connect signals from DLL to slots in EXE
    connect(m_calculator, &Calculator::calculationComplete,
            this, &MainWindow::onCalculationComplete);
    connect(m_calculator, &Calculator::calculationError,
            this, &MainWindow::onCalculationError);

    // Connect button click to calculation method
    connect(m_calculateButton, &QPushButton::clicked,
            this, &MainWindow::onCalculateClicked);

    setWindowTitle("Calculator Using DLL");
    resize(300, 200);
}

MainWindow::~MainWindow()
{
    // Calculator will be automatically deleted as it's a child of MainWindow
}

void MainWindow::onCalculateClicked()
{
    bool okA = false, okB = false;
    int a = m_inputA->text().toInt(&okA);
    int b = m_inputB->text().toInt(&okB);

    if (!okA || !okB) {
        QMessageBox::warning(this, "Input Error", "Please enter valid integers");
        return;
    }

    // Call the DLL method which will eventually emit a signal
    m_calculator->calculate(a, b);
}

void MainWindow::onCalculationComplete(int result)
{
    // This slot handles the signal from DLL
    m_resultLabel->setText(QString("Result: %1").arg(result));
}

void MainWindow::onCalculationError(const QString &errorMessage)
{
    // This slot handles the error signal from DLL
    m_resultLabel->setText(QString("Error: %1").arg(errorMessage));
    QMessageBox::critical(this, "Calculation Error", errorMessage);
}
